import bpy
import os
import math
import bmesh  # <--- 这里添加 bmesh 导入

# 清理场景
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()

# 创建立方体
bpy.ops.mesh.primitive_cube_add(size=2, location=(0, 0, 0))
cube = bpy.context.object
cube.name = "TexturedCube"

# 获取当前脚本目录
script_dir = os.path.dirname(os.path.realpath(__file__))
texture_names = ['front.png', 'back.png', 'left.png', 'right.png', 'top.png', 'bottom.png']

def create_material_with_texture(image_path, mat_name):
    """创建带纹理的材质"""
    mat = bpy.data.materials.new(name=mat_name)
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    
    # 清除默认节点
    nodes.clear()

    # 创建节点
    tex_node = nodes.new('ShaderNodeTexImage')
    bsdf_node = nodes.new('ShaderNodeBsdfPrincipled')
    output_node = nodes.new('ShaderNodeOutputMaterial')

    # 加载纹理
    if os.path.exists(image_path):
        tex_node.image = bpy.data.images.load(image_path)
    else:
        print(f"Texture missing: {image_path}")

    # 连接节点
    links = mat.node_tree.links
    links.new(tex_node.outputs['Color'], bsdf_node.inputs['Base Color'])
    links.new(bsdf_node.outputs['BSDF'], output_node.inputs['Surface'])

    return mat

# 创建六个材质并分配UV
for i, tex in enumerate(texture_names):
    # 创建材质
    mat = create_material_with_texture(
        os.path.join(script_dir, tex),
        f"MAT_{tex.split('.')[0]}"
    )
    
    # 添加材质槽
    if len(cube.data.materials) < i+1:
        cube.data.materials.append(mat)
    
    # UV映射设置
    bpy.context.view_layer.objects.active = cube
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.mesh.select_all(action='DESELECT')
    
    # 选择对应面
    bm = bmesh.from_edit_mesh(cube.data)
    for face in bm.faces:
        if math.isclose(abs(face.normal[i//2]), 1.0, rel_tol=0.1):
            face.select = True
    
    # 指定UV映射坐标
    bpy.ops.uv.smart_project()
    bpy.ops.mesh.select_all(action='DESELECT')
    bpy.ops.object.mode_set(mode='OBJECT')

# 导出OBJ文件
export_path = os.path.join(script_dir, "textured_cube.obj")
bpy.ops.export_scene.obj(
    filepath=export_path,
    use_selection=True,
    use_materials=True,
    path_mode='RELATIVE'
)

print(f"Exported cube to: {export_path}")